from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator
from api.models.audio import Audio
from adminapi.utils.response import success_response, error_response
from datetime import datetime, timedelta
from django.db.models import Q
from decouple import config
from django.utils import timezone

@csrf_exempt
def get_audio_records(request):
    """
    获取音频生成记录
    支持分页、搜索和筛选
    """
    if request.method == 'GET':
        try:
            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            search = request.GET.get('search', '')
            status = request.GET.get('status', '')
            start_date = request.GET.get('start_date', '')
            end_date = request.GET.get('end_date', '')
            
            # 构建查询
            query = Audio.objects.all().order_by('-created_at')
            
            # 搜索条件
            if search:
                query = query.filter(
                    Q(title__icontains=search) |
                    Q(text__icontains=search) |
                    Q(file_name__icontains=search)
                )
            
            # 状态筛选
            if status:
                query = query.filter(status=status)
            
            # 日期范围筛选
            if start_date:
                start_date = datetime.strptime(start_date, '%Y-%m-%d')
                query = query.filter(created_at__gte=start_date)
            if end_date:
                end_date = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
                query = query.filter(created_at__lt=end_date)
            
            # 分页
            paginator = Paginator(query, page_size)
            records = paginator.get_page(page)
            
            # 准备返回数据
            data = {
                'total': paginator.count,
                'total_pages': paginator.num_pages,
                'current_page': page,
                'page_size': page_size,
                'records': []
            }
            
            # 处理每条记录
            for record in records:
                data['records'].append({
                    'id': record.id,
                    'title': record.title,
                    'text': record.text,
                    'voice': record.voice,
                    'rate': record.rate,
                    'volume': record.volume,
                    'style': record.style,
                    'style_degree': record.style_degree,
                    'file_name': record.file_name,
                    'url': record.url,
                    'status': record.status,
                    'status_text': {
                        'pending': '等待处理',
                        'processing': '处理中',
                        'completed': '已完成',
                        'failed': '处理失败'
                    }.get(record.status, '未知状态'),
                    'created_at': timezone.localtime(record.created_at).strftime('%Y-%m-%d %H:%M:%S'),
                    'user': {
                        'id': record.user.id,
                        'nickname': record.user.nickname,
                        'avatar': f"{config('DOMAIN_NAME', default='192.168.220.131')}{record.user.avatar}"
                    } if record.user else None
                })
            
            return success_response(
                message='获取音频记录成功',
                data=data
            )
            
        except Exception as e:
            return error_response(message=f'获取音频记录失败：{str(e)}', code=500)
    else:
        return error_response(message='仅支持GET请求', code=405)
